import axios from 'axios'
import qs from 'qs'
import { baseUrl, startUrl } from './env'
import Toast from 'vant/lib/toast'
// import { getURLParams } from '../utils'

// 全局设置
axios.defaults.baseURL = baseUrl
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
axios.defaults.timeout = 15000
// 添加请求拦截器
axios.interceptors.request.use(function (config) {
  // 在发送请求之前做些什么
  const sessionId = localStorage.getItem('session_id')
  if (sessionId) {
    config.headers['session_id'] = sessionId
  }
  config.data = qs.stringify(config.data)
  return config
}, function (error) {
  // 对请求错误做些什么
  return Promise.reject(error)
})

// 添加响应拦截器
axios.interceptors.response.use(function (response) {
  // 对响应数据做点什么
  Toast.clear()
  if (response.data.success === 'false') {
    if (response.data.errorCode === 'session_expired') {
      localStorage.clear()
      sessionStorage.clear()
      // router.push('/login')
      // window.location.href = startUrl
      // if (getURLParams('code')) {
      //   axios.post(baseUrl + '/rest/login.do', {code: getURLParams('code')}).then((data) => {
      //     if (data.success === 'false') {
      // axios.post(startUrl).then(() => {})
      window.location.replace(startUrl)
      //     } else {
      //       localStorage.setItem('session_id', data.data.session_id)
      //       axios({
      //         method: 'post',
      //         url: baseUrl + '/rest/business/user.do?method=getInfo',
      //         headers: {
      //           'session_id': data.data.session_id
      //         }
      //       }).then((datas) => {
      //         sessionStorage.setItem('userInfo', JSON.stringify(datas.data))
      //       })
      //     }
      //   })
      // }
    }
    // Toast(response.data.errorMsg)
  }
  return response
}, function (error) {
  // 对响应错误做点什么
  Toast.clear()
  Toast('请求异常，请重试')
  return Promise.reject(error)
})

const fetch = function (url, data = {}) {
  return new Promise(function (resolve, reject) {
    axios.post(url, data).then(response => {
      resolve(response.data)
    }).catch(error => {
      reject(error)
    })
  })
}

export default fetch
